<?php

namespace Users\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;

class UserTable
{
    protected $tableGateway;
    
    public function __construct(TableGateway $tableGateway)
    {
	$this->tableGateway = $tableGateway;
    }
    
    public function saveUser(User $user)
    {
	$data = array(
	    'email' => $user->email,
	    'name' => $user->name,
	    'password' => $user->password,
	);
	$id = (int)$user->id;
	if($id == 0)
	{
	    $this->tableGateway->insert($data);
	}
	else
	{
	    if($this->getUser($id))
	    {
		$this->tableGateway->update($data , array('id' => $id));
	    }
	    else
	    {
		throw new \Exception ('User id does not exist');
	    }
	}
    }    
    
    public function getUser($id)
    {
	$id = (int)$id;
	$rowset = $this->tableGateway->select(array('id' => $id));
	$row = $rowset->current();
	if(!$row)
	{
	    throw new \Exception("Could not find row $id");
	}
	return $row;
    }
    
    protected function createUser(array $data)
    {
		$sm = $this->getServiceLocator();
		$dbAdapter = $sm->get('Zend\Db\Adapter\Adaper');
		$resultSetPrototype = new \Zend\Db\ResultSet\ResultSet;
		$resultSetPrototype->setArrayObjectPrototype(new Users\Model\User);
		$tableGateway = new \Zend\Db\TableGateway\TableGateway('user' , $dbAdapter , null , $resultSetPrototype);
		$user = new $User();
		$user->exchangeArray($data);
		$userTable = new UserTable($tableGateway);
		$userTable->saveUser($user);
		return true;
		
    }
}
